package com.myblockchain.p2p;


import com.myblockchain.utility.SpringUtil;
import com.myblockchain.service.P2PService;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * @author Liu
 */
@ServerEndpoint("/test")
@Component
public class P2PServer {


    private P2PService p2PService;
    /**
     * 存放所有在线的客户端
     */
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("有新的客户端连接了: "+ session.getId());
        //将新用户存入在线的组
        p2PService = SpringUtil.getBean(P2PService.class);
        p2PService.addClient(session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("有用户断开了, id为:" + session.getId());
        //将掉线的用户移除在线的组里
        p2PService = SpringUtil.getBean(P2PService.class);
        p2PService.removeClient(session);
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param msg  消息对象
     */
    @OnMessage
    public void onMessage(Session session, String msg) {
        System.out.println("服务端收到客户端发来的消息: {}"+ msg);
        p2PService = SpringUtil.getBean(P2PService.class);
        p2PService.handleMessage(session, msg);

    }

}
